<template>
  <div class="templateManagement" id="templateManagement">
    <div
      :class="isOpenSide ? 'side-left side-close' : 'side-left'"
      @mouseenter="mouseenter"
      @mouseleave="mouseleave"
    >
      <div class="treeBox">
        <div class="buts bottom">
          <a-button class="addButton" type="primary" @click="addCollect">
            <template #icon>
              <span class="iconfont icon-Add iconadd"></span>
            </template>
            新建任务
          </a-button>
        </div>
        <div class="list-box">
          <div class="task-top">
            <span class="iconfont icon-a-Graphiclist"></span>
            <p>采集任务</p>
          </div>
          <div class="task-list">
            <ul>
              <li
                v-for="(item, index) in taskList"
                :class="{ 'checked-active': treeIndex === index }"
                @click="changeTask(item.id, index)"
                :key="index"
              >
                <a-tooltip v-if="item.name.length * 14 > 150" placement="top">
                  <template #title>
                    <span>{{ item.name }}</span>
                  </template>
                  <span class="task-title">{{ item.name }}</span>
                </a-tooltip>
                <span v-else>{{ item.name }}</span>
                <a-tooltip placement="right">
                  <template #title>
                    <span>{{ item.status == 0 ? "未开始 " : "采集中" }}</span>
                  </template>
                  <span>
                    <span
                      :class="
                        item?.status == 0
                          ? 'iconfont icon-Play1'
                          : '  iconfont icon-time1'
                      "
                    ></span>
                  </span>
                </a-tooltip>
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div
        :class="isOpenSide ? 'open-right open-right-side' : 'open-right'"
        v-show="isShowIcon"
        @click="openorhideSide"
      >
        <i
          v-if="isOpenSide"
          class="iconfonts iconfont icon-a-doubleright"
          style="font-size: 20px"
        >
        </i>
        <i
          v-else
          class="iconfonts iconfont icon-a-doubleleft"
          style="font-size: 20px"
        >
        </i>
      </div>
    </div>
    <div class="myResourcesRight">
      <div class="buts">
        <a-button
          v-if="taskList[treeIndex]?.status === 1"
          class="addButton"
          type="primary"
          @click="seeOrEditCollect('See')"
        >
          查看任务
        </a-button>
        <a-button
          v-if="taskList[treeIndex]?.status !== 1"
          class="addButton"
          type="primary"
          @click="seeOrEditCollect('Edit')"
        >
          修改任务
        </a-button>
        <a-button
          v-if="taskList[treeIndex]?.status !== 1"
          class="addButton upload"
          type="primary"
          @click="collectStart"
        >
          开始采集
        </a-button>
        <a-button
          class="addButton1"
          type="primary"
          :disabled="disabled"
          @click="fetchCollectConsume"
        >
          手动入库
        </a-button>
        <a-button
          class="addButton1"
          type="primary"
          :disabled="disabled"
          @click="fetchCollectContent"
        >
          删除数据
        </a-button>
        <a-button
          class="addButton1"
          type="primary"
          @click="fetchCollectContentAll"
        >
          清空所有数据
        </a-button>
        <a-button
          v-if="taskList[treeIndex]?.status !== 1"
          class="addButton1"
          type="primary"
          @click="deleteCollectTask"
        >
          删除任务
        </a-button>
      </div>

      <baseTable
        :columns="columns.templatesColumns"
        :dataSource="gData"
        :isSelect="true"
        :scroll="scroll"
        ref="tagBaseTables"
        :isShowPagination="isShowPagination"
        :showCheckDelete="showCheckDelete"
        :total="total"
        @changePage="changePage"
        disabledParam="status"
        align="middle"
      >
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="column.dataIndex === 'oparation'">
            <span style="color: red">已采集，未入库</span>
          </template>
        </template>
      </baseTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {
  ref,
  computed,
  watch,
  reactive,
  onMounted,
  nextTick,
  createVNode,
} from "vue";
import baseTable from "@/components/table/baseTable.vue";
import { scrollType } from "@/type.d";
import { getTableScroll } from "@/components/table/tableConfig/table";
import columns from "@/components/table/tableConfig/tableColumn/interactionColumn";
import tableToolTip from "@/components/table/tableToolTip.vue";
import { dataSourceType, detailDataItemType } from "@/type";
import { Modal, message } from "ant-design-vue";
import type { TreeProps } from "ant-design-vue";
import request from "@/api/index";
import getters from "@/store/getters";
import { useRouter, useRoute } from "vue-router";
import { routerPerm } from "@/utils/common";
const btnPerm = ref<any[]>([]);

//interface
interface DataList {
  [propName: string | number]: any;
}
interface Options {
  [propName: string | number]: any;
}

// 云端data
const taskList = ref<any[]>([]); // 左侧任务列表
const identity = ref<any>("");
const iframeUrl = ref<any>("");
const treeIndex = ref<number>(0);
const page = ref<number>(1);
const size = ref<number>(10);
const taskId = ref<any>(null);
const cmsData = ref<any>(null);
const userInfo = getters.userInfo();
const siteId = ref(userInfo.siteId);
const isOpenSide = ref<boolean>(false);
const isShowIcon = ref<boolean>(false);
const expandedKeys = ref<(string | number)[]>([]);
const gData = ref<any[]>([]);
const total = ref<any>(0);
const isShowPagination = ref<boolean>(true); // 是否需要配分页器

const showCheckDelete = false; // 是否需要分页器中的自定义
const router = useRouter();
const route = useRoute();
let acceptTypeList = ref<string[]>([]);
const tagBaseTables = ref<any>(null); //
let disabled = ref<any>(true);
//表格数据
let scroll: scrollType = reactive({ y: "", isFixed: false });
nextTick(() => {
  let obj = getTableScroll(74, "contentList", 50);
  scroll.y = obj.y;
  scroll.isFixed = obj.isFixed;
});
let rowSelection = ref<any>(null);
const parentKey = ref<(string | number)[]>([]);

// 获取采集任务详情
const changeTask = (id: any, index: number) => {
  treeIndex.value = index;
  taskId.value = id;
  tagBaseTables.value.selectedRowKeys = [];
  getCollectDetail();
};


const traversal = (data: any) => {
  data.map((item: any) => {
    parentKey.value.push(item.id);
    if (item.children) {
      traversal(item.children);
    }
  });
  expandedKeys.value = parentKey.value;
};
//展开收起侧边栏
const openorhideSide = () => {
  isOpenSide.value = !isOpenSide.value;
};

//侧边栏鼠标移入事件
const mouseenter = () => {
  isShowIcon.value = true;
};

//侧边栏鼠标移出事件
const mouseleave = () => {
  isShowIcon.value = isOpenSide.value ? true : false;
};

// 查看任务or修改任务
const seeOrEditCollect = (type: string) => {
  console.log(type, taskList.value[treeIndex.value].modelType);
  let to = "FastCollectConfig";
  if (taskList.value[treeIndex.value].modelType === "") {
    to = "CustomCollect";
  }
  router.push(
    "/interaction/collect/detail?collectType=" +
      type +
      "&taskId=" +
      taskList.value[treeIndex.value].id +
      "&to=" +
      to
  );
};

// 开始采集
const collectStart = () => {
  const obj = {
    id: taskId.value,
    identity: identity.value,
    appId: cmsData.value.appId,
  };
  getAppIDOrModel(() => {
    isPowerChannels(() => {
      request.fetchCollectTasksStart(obj).then((res: any) => {
        console.log(res);
        router.push(
          "/interaction/collect/detail?collectType=Start&taskId=" + taskId.value
        );
      });
    });
  });
};

// 手动移库
const fetchCollectConsume = () => {
  let keys = rowSelection.value;
  const obj = {
    identity: identity.value,
    appId: cmsData.value.appId,
    taskId: taskId.value,
    ids: keys,
  };
  getAppIDOrModel(() => {
    isPowerChannels(() => {
      request.fetchCollectConsumeByIds(obj).then((res: any) => {
        if (res.code === "00000 00000") {
          message.success(res.message);
          tagBaseTables.value.selectedRowKeys = [];
          getCollectDetail();
        }
      });
    });
  });
};

// 删除数据
const fetchCollectContent = () => {
  let keys = rowSelection.value;
  const obj = {
    data: { ids: keys },
    appId: cmsData.value.appId,
    identity: identity.value,
  };
  Modal.confirm({
    content: "此操作将永久删除该数据, 是否继续?",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      request
        .fetchCollectContent(obj)
        .then((res: any) => {
          if (res.data.code === 200) {
            message.success("操作成功！");
            tagBaseTables.value.selectedRowKeys = [];
            console.log(
              tagBaseTables.value.selectedRowKeys,
              "tagBaseTables.value.selectedRowKeys"
            );
            getCollectDetail();
          } else {
            message.error("操作失败！");
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    },
    onCancel() {},
  });
};

// 清空所有数据
const fetchCollectContentAll = () => {
  const obj = {
    id: taskId.value,
    appId: cmsData.value.appId,
    identity: identity.value,
  };
  Modal.confirm({
    content: "此操作将永久删除该数据, 是否继续?",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      request
        .fetchCollectContentAll(obj)
        .then((res: any) => {
          if (res.data.code === 200) {
            message.success("删除成功！");
            tagBaseTables.value.selectedRowKeys = [];
            getCollectDetail();
          } else {
            message.error("操作失败！");
          }
        })
        .catch((err: any) => {
          throw new Error(err);
        });
    },
    onCancel() {},
  });
};

// computed
rowSelection = computed(() => {
  return tagBaseTables.value?.selectedRowKeys;
});
nextTick(() => {
  watch(
    () => tagBaseTables.value?.selectedRowKeys,
    (newVal, oldVal) => {
      if (newVal && newVal.length < 1) {
        disabled.value = true;
      } else {
        disabled.value = false;
      }
    }
  );
});

acceptTypeList = computed({
  get() {
    return ["html", "vue", "js", "css"];
  },
  set() {},
});

// 分页切换
const changePage = (e: any) => {
  console.log(e.pageSize, e.pageCurrent);
  page.value = e.pageCurrent;
  size.value = e.pageSize;
  getCollectDetail();
};

// 设置云端ID
const setCollectId = () => {
  request.setCollectId().then((res: any) => {
    const result = res.data;
    if (result.code === 200) {
      // console.log(result);
      identity.value = result.data.identity;
      iframeUrl.value = result.data.serverUrl;
      localStorage.setItem("yunIdentity", result.data.identity);
      localStorage.setItem("yunIframeUrl", result.data.serverUrl);
      getAppIDOrModel("");
    }
  });
};
// 获取模型和APPID
const getAppIDOrModel = (callback: any) => {
  console.log(callback, "callback");
  request.fetchCollectGetId().then((res: any) => {
    // console.log(res, '获取appid和栏目模型数据');
    cmsData.value = res;
    localStorage.setItem("appid", res.appId);
    setYunAppIdOrModel();
    if (callback) {
      callback();
    } else {
      getCollectLists();
    }
  });
};
// 左侧任务列表
const getCollectLists = () => {
  const obj = {
    id: cmsData.value.appId,
    identity: identity.value,
    siteId: siteId.value,
  };
  request.fetchCollectTaskList(obj).then((res: any) => {
    if (res.data.code === 200) {
      taskList.value = res.data.data.content;
      if (taskList.value.length > 0) {
        taskId.value = taskList.value[0].id;
        getCollectDetail();
      }
    }
  });
};
// 右侧数据列表
const getCollectDetail = () => {
  const obj = {
    id: taskId.value,
    appId: cmsData.value.appId,
    identity: identity.value,
    size: size.value,
    page: page.value,
  };
  request.fetchCollectContentPage(obj).then((res: any) => {
    // console.log(res.data.data, '任务右侧数据列表');
    if (res.data.code === 200) {
      gData.value = res.data.data.content;
      if (gData.value.length) {
        gData.value.forEach((item: any, index: number) => {
          item.index = index + 1;
        });
      }
      total.value = res.data.data.totalElements;
      isPowerChannels("");
    }
  });
};
// 判断是否有权限，页面加载获取栏目列表，跟当前采集任务进行匹配
const isPowerChannels = (callback: any) => {
  if (callback) callback();
};

// 判断是否有云平台ID
const checkYunId = () => {
  if (
    localStorage.getItem("yunIdentity") === null ||
    localStorage.getItem("yunIdentity") === "" ||
    localStorage.getItem("yunIdentity") === undefined
  ) {
    nextTick(() => {
      setCollectId();
    });
  } else {
    identity.value = localStorage.getItem("yunIdentity");
    iframeUrl.value = localStorage.getItem("yunIframeUrl");
    getAppIDOrModel("");
  }
};
// 设置云端模型和栏目 // 云平台栏目和模型暂时没有映射关系需修复云平台bug
const setYunAppIdOrModel = () => {
  let obj = Object.assign(
    { identity: identity.value, siteId: siteId.value },
    cmsData.value
  );
  // console.log(obj, '设置云端模型');
  request.fetchSetYunAppIdOrModel(obj).then((res: any) => {
    if (res.data.code === 200) {
      // console.log('设置云端模型成功！！！！！');
    }
  });
};

// 新增任务
const addCollect = () => {
  fetchAddCollectEnable();
};
// 检查任务数量限制
const fetchAddCollectEnable = () => {
  const obj = {
    appId: cmsData.value.appId,
    identity: identity.value,
    siteId: siteId.value,
  };
  request.fetchAddCollectEnable(obj).then((res: any) => {
    if (res.data.code === 200 && res.data.data) {
      router.push("/interaction/collect/detail");
    } else {
      message.error('新建任务最大20条！');
    }
  });
};
// 删除任务
const deleteCollectTask = () => {
  Modal.confirm({
    content: "此操作将永久删除该任务, 是否继续?",
    centered: true,
    icon: createVNode("i", {
      class: "iconfont icon-warn warning_ICON",
    }),
    cancelText: "取消",
    okText: "确定",
    onOk: async () => {
      const obj = {
        id: taskId.value,
        appId: cmsData.value.appId,
        identity: identity.value,
      };
      request
        .deleteCollectTask(obj)
        .then((res: any) => {
          if (res.data.code == "200") {
            message.success("操作成功！");
            tagBaseTables.value.selectedRowKeys = [];
            treeIndex.value = 0;
            console.log(taskId.value, "taskId.value");

            getCollectLists();
          } else {
            message.error(res.message);
          }
        })
        .catch((err: any) => {});
    },
    onCancel() {},
  });
};

//onmounted
onMounted(() => {
  // console.log(_path);

  checkYunId();
  // btnPerm.value = routerPerm();
  // fetchTemplateLeftLazyTree("");
});
</script>

<style lang="less" scoped>
.templateManagement {
  width: 100%;
  // background: #fff;
  // padding-bottom: 24px;
  height: calc(100% - 72px);
  display: flex;
  background-color: #fff;
  padding: 16px;
  .list-box {
    margin-top: 10px;
    font-size: 14px;
    .task-top {
      display: flex;
      align-items: center;
      p {
        margin-left: 5px;
      }
    }
  }
  .task-list {
    width: 100%;
    height: calc(100vh - 250px);
    overflow-y: auto;
    li {
      display: flex;
      justify-content: space-between;
      align-items: center;
      line-height: 25px;
      margin-bottom: 4px;
      border-radius: 2px;
      cursor: pointer;
      transition: 0.3s;
      &:hover {
        background-color: #f5f5f5;
      }
      .task-title {
        // width: 160px;
        margin-right: 20px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
  .checked-active {
    background-color: #edf7ff !important;
  }
  .side-left {
    width: 216px;
    height: calc(100% - 24px);
    border-right: 1px solid rgba(0, 0, 0, 0.06);
    padding-right: 4px;
    position: relative;
    transition: width 0.3s;
    padding-right: 24px;

    .iconys {
      transform: translateX(-10px);

      i {
        color: rgb(153, 153, 153);
      }

      span {
        margin-left: 4px;
      }
    }

    .res-tree-menus {
      margin: 0;
      background: #fff;
      z-index: 44;
      position: absolute;
      list-style-type: none;
      min-width: 130px;
      padding: 5px 0;
      box-sizing: border-box;
      border-radius: 4px;
      box-shadow: 0px -3px 16px 0px rgba(89, 155, 255, 0.15);

      li {
        margin: 0;
        padding: 0 20px;
        cursor: pointer;
        font-size: 14px;
        font-weight: 400;
        line-height: 32px;
        color: rgba(0, 0, 0, 0.85);

        &:hover {
          background: rgba(0, 0, 0, 0.04);
        }
      }
    }

    .treeBox {
      height: 100%;
    }

    .treeTitle {
      margin-top: 16px;
      margin-bottom: 4px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 24px;
      background: #edf7ff;
      border-radius: 2px;
      padding: 0 4px;

      .openorclose {
        cursor: pointer;
        display: flex;
        align-items: center;
      }
    }

    .open-right {
      position: absolute;
      top: 50%;
      right: -1px;
      margin-top: -15px;
      bottom: -20px;
      height: 30px;
      width: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      background: #ffffff;
      border: 1px solid rgba(0, 0, 0, 0.06);
      z-index: 2;
    }

    .open-right-side {
      right: -20px;
    }

    .iconfont:hover {
      color: rgba(0, 0, 0, 0.6);
    }

    .iconfonts {
      color: rgba(0, 0, 0, 0.45);
    }
  }

  .side-close {
    width: 0;
    transition: width 0.3s;

    .treeBox {
      display: none;
    }
  }

  .myResourcesRight {
    width: 500px;
    border-left: 1px solid rgba(0, 0, 0, 0.06);
    flex: 1;
    height: 100%;
    padding: 0 24px;
  }

  .buts {
    display: flex;

    .addButton:last-child {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 16px;
    }
    .addButton1 {
      margin-left: 16px;
    }

    .upload {
      margin-left: 16px;
    }
  }

  .bottom {
    margin-bottom: 7px;
  }

  :deep(.ant-table-thead .ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    padding-right: 16px;
  }

  :deep(.ant-table-cell:nth-last-of-type(1)) {
    text-align: right;
    margin-right: 16px;
  }

  .eidtRecords {
    margin-right: 16px;
  }

  .eidtRecords:last-child {
    margin-right: 0;
  }

  ::v-deep(.titleBox) {
    display: flex;
    align-items: center;
    justify-items: center;

    // height: 29px;
    // line-height: 29px;
    // height: 18px;
    .titleTip {
      flex: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      margin-left: 16px;
    }

    .tabletypeImgBox {
      width: 80px;
      height: 80px;
      padding: 8px;
      background: #ffffff;
      border-radius: 2px;
      border: 1px solid rgba(0, 0, 0, 0.15);
    }

    .tabletypeImg {
      max-width: 64px;
      width: auto;
      max-height: 64px;

      height: auto;
      margin: auto;
      //   width: 16px;
      //   height: 16px;
      // line-height: 18px;
    }
  }

  ::v-deep(.ant-table-cell) {
    vertical-align: middle;
  }
}

.icon-a-Folder-openwenjianjia-kai {
  color: #ffca28;
}

.contentIndexLeft {
  padding-right: 24px;
  width: 216px;
  height: 100%;
}

::v-deep(::-webkit-scrollbar) {
  height: 10px;
}

::v-deep(.side-left .ant-tree-list-holder) {
  width: auto;
  height: 100%;
  transition: width 0.3s;
}

::v-deep(.side-close .ant-tree-list-holder) {
  width: 0;
  height: 100%;
  transition: width 0.3s;
}

::v-deep(.side-left .ant-tree-list:hover .ant-tree-list-scrollbar) {
  display: block !important;
}

::v-deep(.ant-tree-list .ant-tree-list-scrollbar) {
  display: none !important;
}

::v-deep(.ant-tree-list-scrollbar-thumb) {
  background: rgba(0, 0, 0, 0.15) !important;
}

::v-deep(.ant-checkbox + span) {
  padding-left: 12px;
  padding-right: 0;
}

::v-deep(.ant-table-wrapper) {
  margin-top: 24px;
}

::v-deep(.ant-table-thead > tr > th) {
  // padding: 16px 0 16px 16px;
}

table tr th.ant-table-selection-column,
table tr td.ant-table-selection-column {
  padding-right: 8px;
  padding-left: 8px;
  text-align: left;
}
</style>
<style lang="less">
.side-left {
  .ant-input-search {
    margin-top: 16px;
  }

  .ant-tree {
    height: calc(100% - 88px);
    overflow: auto;

    .ant-tree-treenode {
      width: 100%;

      .ant-tree-node-content-wrapper {
        width: 100%;
      }
    }

    .ant-tree::-webkit-scrollbar {
      display: none;
    }

    .ant-tree:hover::-webkit-scrollbar {
      display: block;
    }

    .ant-tree-list-scrollbar-thumb {
      height: auto !important;
    }

    .ant-tree-list-holder {
      overflow-y: unset !important;
    }
  }
}

.fileFlags {
  display: flex;
  align-items: center;

  .iconfont {
    margin-right: 4px;
  }

  img {
    margin-right: 4px;
  }
}

.fileName {
  max-width: 260px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
